﻿/**
* This jQuery plugin displays pagination links inside the selected elements.
* 
* This plugin needs at least jQuery 1.4.2
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 2.0rc
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
*/
(function ($) {
    /**
    * @class Class for calculating pagination values
    */
    $.PaginationCalculator = function (maxentries, opts) {
        this.maxentries = maxentries;
        this.opts = opts;
    }

    $.extend($.PaginationCalculator.prototype, {
        /**
        * Calculate the maximum number of pages
        * @method
        * @returns {Number}
        */
        numPages: function () {
            return Math.ceil(this.maxentries / this.opts.items_per_page);
        },
        /**
        * Calculate start and end point of pagination links depending on 
        * current_page and num_display_entries.
        * @returns {Array}
        */
        getInterval: function (current_page) {
            var ne_half = Math.ceil(this.opts.num_display_entries / 2);
            var np = this.numPages();
            var upper_limit = np - this.opts.num_display_entries;
            var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
            var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(this.opts.num_display_entries, np);
            return { start: start, end: end };
        }
    });

    // Initialize jQuery object container for pagination renderers
    $.PaginationRenderers = {}

    /**
    * @class Default renderer for rendering pagination links
    */
    $.PaginationRenderers.defaultRenderer = function (maxentries, opts) {
        this.maxentries = maxentries;
        this.opts = opts;
        this.pc = new $.PaginationCalculator(maxentries, opts);
    }
    $.extend($.PaginationRenderers.defaultRenderer.prototype, {
        /**
        * Helper function for generating a single link (or a span tag if it's the current page)
        * @param {Number} page_id The page id for the new item
        * @param {Number} current_page 
        * @param {Object} appendopts Options for the new item: text and classes
        * @returns {jQuery} jQuery object containing the link
        */
        createLink: function (page_id, current_page, appendopts) {
            var lnk, np = this.pc.numPages();
            page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1); // Normalize page id to sane value
            appendopts = $.extend({ text: page_id + 1, classes: "" }, appendopts || {});
            if (page_id == current_page) {
                lnk = $("<span> " + appendopts.text + " </span>");
            }
            else {
                lnk = $("<a>" + appendopts.text + "</a>")
					.attr('href', this.opts.link_to.replace(/__id__/, page_id));
            }


            if (appendopts.classes) { lnk.addClass(appendopts.classes); }
            lnk.data('page_id', page_id);
            var lnkLi = $("<li></li>");
            lnk.appendTo(lnkLi);
            return lnkLi;
        },
        // Generate a range of numeric links 
        appendRange: function (container, current_page, start, end) {
            var i;
            for (i = start; i < end; i++) {
                this.createLink(i, current_page).appendTo(container);
            }
        },
        getLinks: function (current_page, eventHandler) {
            var begin, end,
				interval = this.pc.getInterval(current_page),
				np = this.pc.numPages(),
				fragment = $("<div class='paging_view'></div>");
            var tfragment = $("<ul></ul>");
            // Generate "Previous"-Link

            if (this.opts.prev_text && (current_page > 0 || this.opts.prev_show_always)) {

                tfragment.append(this.createLink(current_page - 1, current_page, { text: this.opts.prev_text, classes: "nocolor" }));
            }
            // Generate starting points
            if (interval.start > 0 && this.opts.num_edge_entries > 0) {
                end = Math.min(this.opts.num_edge_entries, interval.start);
                this.appendRange(tfragment, current_page, 0, end);
                if (this.opts.num_edge_entries < interval.start && this.opts.ellipse_text) {
                    jQuery("<li><span>" + this.opts.ellipse_text + "</span></li>").appendTo(tfragment);
                }
            }
            // Generate interval links
            this.appendRange(tfragment, current_page, interval.start, interval.end);
            // Generate ending points
            if (interval.end < np && this.opts.num_edge_entries > 0) {
                if (np - this.opts.num_edge_entries > interval.end && this.opts.ellipse_text) {
                    jQuery("<li><span>" + this.opts.ellipse_text + "</span></li>").appendTo(tfragment);
                }
                begin = Math.max(np - this.opts.num_edge_entries, interval.end);
                this.appendRange(tfragment, current_page, begin, np);

            }
            // Generate "Next"-Link
            if (this.opts.next_text && (current_page < np - 1 || this.opts.next_show_always)) {
                tfragment.append(this.createLink(current_page + 1, current_page, { text: this.opts.next_text, classes: "nocolor" }));
            }
            $('a', tfragment).click(eventHandler);

            
            tfragment.appendTo(fragment);
            return fragment;
        }
    });

    // Extend jQuery
    $.fn.pagination = function (maxentries, opts) {

        // Initialize options with default values
        opts = jQuery.extend({
            items_per_page: 10,
            num_display_entries: 10,
            current_page: 0,
            num_edge_entries: 0,
            link_to: "#",
            prev_text: "Prev",
            next_text: "Next",
            ellipse_text: "...",
            prev_show_always: true,
            next_show_always: true,
            renderer: "defaultRenderer",
            callback: function () { return false; }
        }, opts || {});

        var containers = this,
		renderer, links, current_page;


        /**
        * This is the event handling function for the pagination links. 
        * @param {int} page_id The new page number
        */
        function pageSelected(evt) {
            var links;
            //由于翻页换成了img，所以evt.target需要判断到底是a还是img
            var current_page = evt.target.tagName.toLowerCase() == "a"
                    ? $(evt.target).data('page_id')
                    : $(evt.target).parent().data('page_id');
            containers.data('current_page', current_page);
            links = renderer.getLinks(current_page, pageSelected);
            containers.empty();
            links.appendTo(containers);
            var continuePropagation = opts.callback(current_page, containers);
            if (!continuePropagation) {
                if (evt.stopPropagation) {
                    evt.stopPropagation();
                }
                else {
                    evt.cancelBubble = true;
                }
            }
            return continuePropagation;
        }

        current_page = opts.current_page;
        containers.data('current_page', current_page);
        // Create a sane value for maxentries and items_per_page
        maxentries = (!maxentries || maxentries < 0) ? 1 : maxentries;
        opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0) ? 1 : opts.items_per_page;

        if (!$.PaginationRenderers[opts.renderer]) {
            throw new ReferenceError("Pagination renderer '" + opts.renderer + "' was not found in jQuery.PaginationRenderers object.");
        }
        renderer = new $.PaginationRenderers[opts.renderer](maxentries, opts);

        containers.each(function () {
            // Attach control functions to the DOM element 
            this.selectPage = function (page_id) { pageSelected(page_id); }
            this.prevPage = function () {
                var current_page = containers.data('current_page');
                if (current_page > 0) {
                    pageSelected(current_page - 1);
                    return true;
                }
                else {
                    return false;
                }
            }
            this.nextPage = function () {
                var current_page = containers.data('current_page');
                if (current_page < numPages() - 1) {
                    pageSelected(current_page + 1);
                    return true;
                }
                else {
                    return false;
                }
            }
        });
        // When all initialisation is done, draw the links
        links = renderer.getLinks(current_page, pageSelected);
        containers.empty();
        links.appendTo(containers);



        //当页数为1时不显示-
        if (Math.ceil(maxentries / opts.items_per_page) < 2) {
            $(this).empty();
        }

        // call callback function
        //禁止首次生成分页器时回调-
        //opts.callback(current_page, containers);

    }



})(jQuery);

//默认初始化
(function ($) {
    $.fn.paginationex = function (webRoot, rowcount, pagesize, currentpage, callbackfunc) {
        //先强转INT，字符参数将导致错误20100629

        //  alert("当前页:"+currentpage)
        rowcount = parseInt(rowcount);
        psize = parseInt(pagesize);
        currentpage = parseInt(currentpage)
        $(this).pagination(rowcount, {
            callback: callbackfunc,
            prev_text: '上一页',//'<img src="'+webRoot+'images/blue_sj_icon.gif">',
            next_text: '下一页',//'<img src="'+webRoot+'images/blue_sj_icon2.gif">',
            prev_show_always: false,
            next_show_always: false,
            items_per_page: pagesize,
            num_display_entries: 5,
            current_page: currentpage,
            num_edge_entries: 1
        });
    }

    $.fn.paginationexmini = function (rowcount, pagesize, currentpage, callbackfunc) {
        //先强转INT，字符参数将导致错误20100629
        rowcount = parseInt(rowcount);
        psize = parseInt(pagesize);
       
        currentpage = parseInt(currentpage)
        $(this).pagination(rowcount, {
            callback: callbackfunc,
            prev_text: '<<',
            next_text: '>>',
            prev_show_always: false,
            next_show_always: false,
            items_per_page: pagesize,
            num_display_entries: 5,
            current_page: currentpage,
            num_edge_entries: 1
        });
    }
})($);
